import cv2
import numpy as np
frame1=cv2.imread("img.png")
cap=cv2.VideoCapture(0)
while True:
    _,frame=cap.read()
    img_HSV=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    kernel_2=np.ones((2,2),np.uint8)
    kernel_3=np.ones((3,3),np.uint8)
    kernel_4=np.ones((4,4),np.uint8)

    lower=np.array([100,43,46])
    higher=np.array([124,255,255])
    mask=cv2.inRange(img_HSV,lower,higher)
    erosion=cv2.erode(mask,kernel_4,iterations=1)
    erosion=cv2.erode(erosion,kernel_4,iterations=1)
    dilation=cv2.dilate(erosion,kernel_4,iterations=1)
    dilation=cv2.dilate(dilation,kernel_4,iterations=1)

    target=cv2.bitwise_and(frame,frame,mask=dilation)
    ret,binary=cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)
    contours,hierarchy=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    height = frame.shape[0]
    width = frame.shape[1]
    cv2.rectangle(frame, (height // 2 - 100, 0), (height // 2 + 200, width), (0, 255), 3)
    if len(contours) >0:
        x,y,w,h=cv2.boundingRect(contours[-1])
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255),3)
        center_x=x+w//2
        center_y=y+h//2
        if center_x >(height // 2 + 200):
            print("往左")
        elif center_x <(height // 2 -100):
            print("往右")
        else :
            print("walk")
        cv2.circle(frame,(center_x,center_y),5,(0,0,255),-1)

    cv2.imshow('IMG',frame)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

